package com.lxhdj.codegenerator;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CodeGenerator {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator generator = new AutoGenerator(dbConfig());
        // 策略配置
        generator.strategy(strategyConfig());
        // 全局配置
        generator.global(globalConfig());
        // 包配置
        generator.packageInfo(packageConfig());
        // 自定义输出文件
        // generator.injection(injectionConfig());

        // 执行生成
        generator.execute();
    }

    public static void test(){
        String projectPath = System.getProperty("user.dir");
        FastAutoGenerator.create("jdbc:mysql://39.106.0.169:3306/guotai-cloudshop-dev?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true",
                        "cloud_shop",
                        "cloud_shop")
                .globalConfig(builder -> {
                    builder.author("shooke") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .outputDir(projectPath + "/src/main/java"); // 指定输出目录
                })
                // 包配置
                .packageConfig((scanner, builder) -> {
                    builder.parent("com.lxhdj") // 设置父包名
                            .moduleName(scanner.apply("请输入模块名")) // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, projectPath + "/src/main/resources/mapper/")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("salesman") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 首字母小写
     *
     * @param name
     * @return
     */
    public static String toCamel(String name) {
        if (org.apache.commons.lang3.StringUtils.isBlank(name)) {
            return null;
        }
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

    /**
     * 数据库链接
     * @return
     */
    private static DataSourceConfig dbConfig(){
        return new DataSourceConfig
                .Builder("jdbc:mysql://localhost:33066/rcm?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true",
                        "root",
                        "123456")
                .schema("mybatis-plus")
                .keyWordsHandler(new MySqlKeyWordsHandler())
                .build();
    }

    /**
     * 全局配置
     * @return
     */
    private static GlobalConfig globalConfig() {
        String projectPath = System.getProperty("user.dir");
        // String projectPath = "D:\\";
        System.out.println(projectPath);
        return new GlobalConfig.Builder()
                .outputDir(projectPath + "/src/main/java")
                .author("shooke")
                .fileOverride()
                .disableOpenDir()
                .build();
    }

    /**
     * 包配置
     * @return
     */
    private static PackageConfig packageConfig(){
        String projectPath = System.getProperty("user.dir");
        return new PackageConfig.Builder()
                .parent("com.lxhdj")
                .moduleName(scanner("模块名"))
                .entity("model")
                .mapper("dao")
                .controller("controller")
                .pathInfo(Collections.singletonMap(OutputFile.xml, projectPath + "/src/main/resources/mapper/"))
                .build();
    }
    private static StrategyConfig strategyConfig(){
        return new StrategyConfig.Builder()
                .addInclude(scanner("表名，多个英文逗号分割").split(",")).addTablePrefix("t_", "c_")
                .controllerBuilder().enableRestStyle().enableHyphenStyle()
                .entityBuilder().formatFileName("%sModel").enableLombok()
                .mapperBuilder().formatMapperFileName("%sDao")
                .serviceBuilder().formatServiceFileName("%sService").formatServiceImplFileName("%sServiceImp")
                .build();
    }
    /**
     * 自定义输出文件
     * @return
     */
    private static InjectionConfig injectionConfig(){
        String projectPath = System.getProperty("user.dir");
        Map<String, String> customFile = new HashMap<>();
        customFile.put("test.txt", "/templates/mapper.xml.vm");
        return new InjectionConfig.Builder()
                .beforeOutputFile((tableInfo, objectMap) -> {
                    // customFile.put(projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                    //         + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML, "/templates/mapper.xml.vm");


                    System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                })
                .customFile(Collections.singletonMap("test.txt", "/templates/test.vm"))
                .build();
    }


}
